﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Text;

/// <summary>
///Tools 的摘要说明
/// </summary>
public class Tools
{

    /// <summary>
    /// 对表中的数据排序
    /// </summary>
    /// <param name="dt">要排序的表</param>
    /// <param name="sortStr">要排序的列名，如  "columname1,columnname2,columnname3" 则依次地对columname1、columnname2、columnname3排序</param>
    /// <param name="isDESC">true 则为降序排序</param>
    /// <returns></returns>
    public static DataTable RankDT(DataTable dt, string sortStr, bool isDESC)
    {
        string desec="";
        if (isDESC) desec="DESC";
        int count = dt.Rows.Count;
        DataView dataView = dt.DefaultView;
        dataView.Sort = sortStr + " " + desec;
        DataTable dt2 = dt.Clone();
        DataRow rowTemp;
        dt2 = dataView.ToTable();
        //for (int j = 0; j < count; j++)
        //{
        //    rowTemp = dt2.NewRow();
        //    rowTemp.ItemArray = dataView[j].Row.ItemArray;
        //    dt2.Rows.Add(rowTemp);
        //}
        return dt2;

    }

    public static DataTable RankDT(DataTable dt, int index, bool isDESC)
    {
        string desec = "ASC";
        if (isDESC) desec = "DESC";
        int count = dt.Rows.Count;

        DataView dataView = dt.DefaultView;
        dataView.Sort = dt.Columns[dt.Columns.Count - index] + " desc";
        
        dt = dataView.ToTable();

        return dt;

    }
    /// <summary>
    /// 重新构造DataTable，让其所有列的数据都为string类型(可在参数中定义排除列)
    /// </summary>
    /// <param name="dt">要排序的表</param>
    /// <param name="columns">指定不需要重构的列名，如  "columname1,columnname2,columnname3"。</param>
    /// <returns></returns>
    public static DataTable RestructDTColumn(DataTable dt, string columns)
    {
        DataTable dt2=new DataTable();
        string[] exceptColNames = ToolsService.StringTools.ToolsLevel0.Split(columns, ',');
        DataRow rowx;
        if (dt != null && dt.Columns.Count > 0)
        {
            foreach (DataColumn co in dt.Columns)
            {
                if (!ToolsService.StringTools.ToolsLevel0.Contains(exceptColNames, co.ColumnName))
                { dt2.Columns.Add(new DataColumn(co.ColumnName, typeof(string))); }
                else {
                    dt2.Columns.Add(new DataColumn(co.ColumnName, co.DataType));
                }
                   
            }
        
        }
        foreach (DataRow row in dt.Rows)
        {
            rowx = dt2.NewRow();
            foreach (DataColumn co in dt2.Columns)
            {
                rowx[co.ColumnName] = row[co.ColumnName].ToString();
            }
            dt2.Rows.Add(rowx);
        }
        return dt2;

    }

    /// <summary>
    /// 把所有列的值设为同一值
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static DataRow SetRowValue(DataRow row,object value)
    {
        int len=row.ItemArray.Length ;
        for (int i = 0; i < len; i++)
        { 
          row[i]=value;
        }
        return row;
    }

    public static string StringArrayToString(string[] v_str)
    {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < v_str.Length; i++)
        {
            if (i > 0) str.Append(',');
            str.Append(str[i]);
        }
        return str.ToString();
    }


    /// <summary>
    /// 格式化DataTable里的所有日期字段，如 "2011-3-12"将被格式化为 "2011-03-12"
    /// </summary>
    public static DataTable FormatDataTableDateColumn(DataTable dt, params string[] columnNames)
    {

        if (dt == null | columnNames.Length <= 0) return dt;
        int colmunsCount = dt.Columns.Count;
        DateTime newdt;
        foreach (DataRow row in dt.Rows)
        {
            for (int i = 0; i < columnNames.Length; i++)
            {
                string ss = row[columnNames[i]].ToString();

                if (DateTime.TryParse(ss, out  newdt))
                {
                    string sss = FormatDate(ss);
                    try
                    {
                        row[columnNames[i]] = sss;
                    }
                    catch (Exception ex) { row[columnNames[i]] = DateTime.Parse(sss); }
                }
            }
        }
        return dt;
    }

    /// <summary>
    /// 格式化日期字符串，如 "2011-3-12"将被格式化为 "2011-03-12"
    /// </summary>
    public static string FormatDate(string dateStr)
    {
        if (dateStr == null) return dateStr;
        DateTime dt;
        if (DateTime.TryParse(dateStr, out dt))
        {
            return dt.ToString("yyyy-MM-dd");
        }
        else
        {
            return dateStr;
        }
    }

    public static string ToEasyUIDataGridJson(string rowsJson, int count)
    {
        return string.Format("{{\"total\":{0},\"rows\":{1}}}", count, rowsJson);
    }

    /// <summary>
    /// 当 fields为null时，即生成所有列的数据。返回 [{'id':12,'column1':'12'},{'id':13,'column1':'12'}]格式的json
    /// </summary>
    public static string ToEasyUIJson(DataTable tableSource, params string[] fields)
    {
        if (tableSource == null) return "";
        int columnCount = tableSource.Columns.Count;
        int rowCount = tableSource.Rows.Count;
        if (fields == null)
        {

            fields = new string[columnCount];
            System.Text.StringBuilder aa = new System.Text.StringBuilder();
            for (int i = 0; i < columnCount; i++)
            {
                fields[i] = tableSource.Columns[i].ColumnName;

                // aa.AppendLine("<th field=\"" + tableSource.Columns[i].ColumnName + "\" width=\"100\">" + tableSource.Columns[i].ColumnName + "</th>");
                //aa.AppendLine("{field:\"" + tableSource.Columns[i].ColumnName + "\",title:\"" + tableSource.Columns[i].ColumnName + "\",width:80},");
            }
            // string cc = aa.ToString();
        }
        if (fields.Length < 1) return "";
        string jsonData = "[";

        if (rowCount > 0)
        {
            foreach (DataRow row in tableSource.Rows)
            {
                jsonData += "{";
                for (int i = 0; i < fields.Length; i++)
                {
                    string filedData = row[fields[i]].ToString();
                    filedData = filedData.Replace("\\", "/");
                    jsonData += "\"" + fields[i] + "\":\"" + filedData + "\",";
                }
                jsonData = jsonData.Substring(0, jsonData.Length - 1);
                jsonData += "},";
            }
            jsonData = jsonData.Substring(0, jsonData.Length - 1);
            jsonData += "]";
        }
        else
        {
            jsonData += "]";
        }
        return jsonData;
    }

    /// <summary>
    /// 将tmpDataTable的所有行转成Excel可直接读取的字符串文本。
    /// columns指定要转的列，columns[?,0]为列名，columns[?,1]为访列名的别名(可以为中文)。
    /// </summary>
    public static string DataTabletoExcel(DataTable tmpDataTable, string[,] columnsHashtalbe)
    {
        string t = "\t";
        string n = System.Environment.NewLine;
        if (tmpDataTable == null) return "";

        int rowNum = tmpDataTable.Rows.Count;

        int columnNum = tmpDataTable.Columns.Count;
        int needCreateCloumnNum = columnsHashtalbe.GetLength(0);
        int lastColumnIndex = needCreateCloumnNum - 1;


        StringBuilder tempString = new StringBuilder();






        //将DataTable的列名导入Excel表第一行

        for (int i = 0; i < needCreateCloumnNum; i++)
        {

            tempString.Append( columnsHashtalbe[i, 1]);
            if (i == lastColumnIndex)tempString.Append(  n); else tempString.Append( t);

        }

        //将DataTable中的数据导入Excel中
        string rowdata;
        for (int i = 0; i < rowNum; i++)
        {
            for (int j = 0; j < needCreateCloumnNum; j++)
            {

                try
                {
                    rowdata = tmpDataTable.Rows[i][columnsHashtalbe[j, 0]].ToString();
                }
                catch (Exception ex) { rowdata = ""; }
               tempString.Append( rowdata);
                if (j == lastColumnIndex) tempString.Append(  n); else tempString.Append( t);


            }

        }
        return tempString.ToString();

    }

    public string CreateGUID()
    {
        return Guid.NewGuid().ToString().Replace("-", "");
    }

}
